package cn.jksoft.businessclient.ui.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jksoft.businessclient.R;
import cn.jksoft.businessclient.api.ReceivingApi;
import cn.jksoft.businessclient.api.ReceivingService;
import cn.jksoft.businessclient.base.BaseApplication;
import cn.jksoft.businessclient.base.BaseSwipeBackCompatActivity;
import cn.jksoft.businessclient.bean.BaseEntity;
import cn.jksoft.businessclient.bean.CustCardEntity;
import cn.jksoft.businessclient.bean.OrderDetailEntity;
import cn.jksoft.businessclient.ui.adapter.OrderSettlementDetailAdapter;
import cn.jksoft.businessclient.ui.views.RecycleViewDivider;
import cn.jksoft.businessclient.utils.CommonUtils;
import cn.jksoft.businessclient.utils.DensityUtils;
import cn.jksoft.businessclient.utils.DialogHelp;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by RogersHuang on 16/4/12.
 */
public class OrderSettlementActivity extends BaseSwipeBackCompatActivity implements View.OnClickListener {

    private static final int REQUEST_SELECT_CUSTOMER = 1000;

    @Bind(R.id.tv_order_price)
    TextView tvOrderPrice;
    @Bind(R.id.tv_discount_price)
    TextView tvDiscountPrice;
    @Bind(R.id.tv_discount_name)
    TextView tvDiscountName;
    @Bind(R.id.tv_pay_price)
    TextView tvPayPrice;
    @Bind(R.id.btn_confirm)
    AppCompatButton btnConfirm;

    private View rootview;
    private PopupWindow popupOrderSettlement;
    private OrderSettlementDetailAdapter mAdapter;
    private ProgressDialog waitDialog;
    private OrderDetailEntity mEntity;
    private Menu mMenu;
    private long memberId = -1;
    private String prodSkuIds = "";
    private float payPrice;
    private float totalDiscountPrice = 0;
    private String isFastBillingOrder = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_settlement);
        ButterKnife.bind(this);
        initTitle("收款单");
        initBackClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getIntent().getBooleanExtra("isFastCreate", false)) {
                    Intent intent = new Intent();
                    intent.setClass(OrderSettlementActivity.this, MainActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);//它可以关掉所要到的界面中间的activity
                    startActivity(intent);
                }
                finish();
            }
        });
        loadOrderProductData();
        tvDiscountPrice.setText("无");
        btnConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                settlementOrder();
            }
        });
    }

    private void initPopup() {

        if (rootview == null) {
            rootview = getLayoutInflater().inflate(R.layout.popup_order_settlement_detail, null);
        }
        // 创建PopupWindow对象
        popupOrderSettlement = new PopupWindow(rootview, ViewGroup.LayoutParams.MATCH_PARENT,
                DensityUtils.getDisplayHeight(this) - CommonUtils.getToolbarHeight(this) - DensityUtils.getStatusBarHeight(this));

        popupOrderSettlement.setAnimationStyle(R.style.shopping_car_animstyle);
        //设置PopupWindow弹出窗体的背景
        popupOrderSettlement.setBackgroundDrawable(new BitmapDrawable());
        popupOrderSettlement.setOutsideTouchable(true);// 以及下一句 同时写才会有效
        popupOrderSettlement.setFocusable(true);// 获取焦点
        ImageView ivClose = (ImageView) rootview.findViewById(R.id.iv_close);
        ivClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupOrderSettlement.dismiss();
            }
        });
        RelativeLayout layout = (RelativeLayout) rootview.findViewById(R.id.recyclerview_layout);
        TextView tvTotalPrice = (TextView) rootview.findViewById(R.id.tv_all_discount_price);
        tvTotalPrice.setText("-￥" + totalDiscountPrice);
        ImageView ivEmpty = (ImageView) rootview.findViewById(R.id.iv_empty);
        ivEmpty.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupOrderSettlement.dismiss();
            }
        });
        ;
        RecyclerView mRecyclerView = (RecyclerView) rootview.findViewById(R.id.pop_recyclerview);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.VERTICAL));
        mAdapter = new OrderSettlementDetailAdapter(this, mEntity.getOrderDetails().getOrderItemsList());
        mRecyclerView.setAdapter(mAdapter);
        popupOrderSettlement.setFocusable(true);
        popupOrderSettlement.setAnimationStyle(R.style.shopping_car_animstyle);
        int popHeight = DensityUtils.dip2px(this, 45 * (mEntity.getOrderDetails().getOrderItemsList().size() > 6 ? 6 : mEntity.getOrderDetails().getOrderItemsList().size()) + 45 + 16);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, popHeight);
        layout.setLayoutParams(layoutParams);
        popupOrderSettlement.showAtLocation(btnConfirm,
                Gravity.BOTTOM, 0, 0);
    }

    private void loadOrderProductData() {
        waitDialog = DialogHelp.getWaitDialog(this, "正在加载...");
        waitDialog.show();
        JSONObject json = null;
        try {
            json = new JSONObject();
            json.put("outboundId", getIntent().getStringExtra("outboundId"));
            json.put("messId", getIntent().getStringExtra("messageId"));
            json.put("operId", BaseApplication.getInstance().getLoginEntity().getPuxsoftLoginDTO().getAdminUserId());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        ReceivingApi service = ReceivingService.createReceivingService();
        service.getOrderDetailProductList(json.toString())
                .observeOn(Schedulers.io())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<OrderDetailEntity>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        waitDialog.dismiss();
                    }

                    @Override
                    public void onNext(OrderDetailEntity entity) {

                        String retCode = entity.getIs_successful();
                        if ("1".equals(retCode)) {
                            isFastBillingOrder = entity.getOrderDetails().getIS_FAST_BILLING_ORDER();
                            if ("1".equals(isFastBillingOrder)) {
                                hiddenEditMenu();
                            } else {
                                showEditMenu();
                            }
                            mEntity = entity;
                            payPrice = entity.getOrderDetails().getORDER_TOTAL_MONEY() / 100;
                            tvOrderPrice.setText("￥" + entity.getOrderDetails().getORDER_TOTAL_MONEY() / 100);
                            tvPayPrice.setText("￥" + entity.getOrderDetails().getORDER_TOTAL_MONEY() / 100);
                            for (OrderDetailEntity.OrderDetailsBean.OrderItemsListBean bean : entity.getOrderDetails().getOrderItemsList()) {
                                prodSkuIds = prodSkuIds + bean.getPROD_SKU_ID() + ",";
                            }
                            getMemberCount();
                        }
                        waitDialog.dismiss();
                    }
                });
    }

    private void settlementOrder() {
        waitDialog = DialogHelp.getWaitDialog(this, "正在结算...");
        waitDialog.show();
        JSONObject json = null;
        try {
            json = new JSONObject();
            json.put("outboundId", getIntent().getStringExtra("outboundId"));
            json.put("storeId", BaseApplication.getInstance().getLoginEntity().getPuxsoftLoginDTO().getStoreId() + "");
            json.put("operId", BaseApplication.getInstance().getLoginEntity().getPuxsoftLoginDTO().getAdminUserId() + "");
            json.put("customerId", mEntity.getOrderDetails().getCUSTOMER_ID() + "");
            json.put("tenantId", BaseApplication.getInstance().getLoginEntity().getPuxsoftLoginDTO().getTenantId() + "");
            if (memberId > 0) {
                json.put("memberId", memberId);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        ReceivingService.createReceivingService().settleMentOrder(json.toString())
                .observeOn(Schedulers.io())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseEntity>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        waitDialog.dismiss();
                    }

                    @Override
                    public void onNext(BaseEntity entity) {
                        if ("1".equals(entity.getIs_successful())) {
                            showToast("结算成功");
                            if (getIntent().getBooleanExtra("isFastCreate", false)) {
                                Intent intent = new Intent();
                                intent.setClass(OrderSettlementActivity.this, MainActivity.class);
                                intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);//它可以关掉所要到的界面中间的activity
                                startActivity(intent);
                                finish();
                            } else {
                                setResult(RESULT_OK, getIntent());
                                finish();
                            }
                        } else {
                            Intent intent = new Intent();
                            intent.setClass(OrderSettlementActivity.this, MainActivity.class);
                            intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);//它可以关掉所要到的界面中间的activity
                            startActivity(intent);
                            finish();
                            showToast(entity.getResult() != null ? entity.getResult() : "结算失败");
                        }
                        waitDialog.dismiss();
                    }
                });
    }


    private void getMemberCount() {
        JSONObject json = null;
        try {
            json = new JSONObject();
            BaseApplication.getInstance().getLoginEntity().getPuxsoftLoginDTO().getAdminUserId();
            json.put("storeId", BaseApplication.getInstance().getLoginEntity().getPuxsoftLoginDTO().getStoreId());//BaseApplication.getInstance().getLoginEntity().getPuxsoftLoginDTO().getStoreId()+"");
            json.put("customerId", mEntity.getOrderDetails().getCUSTOMER_ID());
            json.put("custCmId", mEntity.getOrderDetails().getCUST_CM_ID());
            json.put("prodSkuIds", prodSkuIds);
        } catch (Exception e) {
            e.printStackTrace();
        }

        ReceivingApi service = ReceivingService.createReceivingService();
        service.qryCustomerCardList(json.toString())
                .observeOn(Schedulers.io())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<CustCardEntity>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(CustCardEntity custCardEntity) {

                        if ("1".equals(custCardEntity.getIs_successful())) {
                            if (custCardEntity.getCustomerCardList() != null && custCardEntity.getCustomerCardList().size() > 0) {
                                tvDiscountPrice.setText(custCardEntity.getCustomerCardList().size() + "张可用");
                                tvDiscountPrice.setTextColor(getResources().getColor(R.color.orange));
                            }
                        }
                    }
                });

    }


    @Override
    @OnClick({R.id.ll_member, R.id.ll_order_price})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_member:
                totalDiscountPrice = 0;
                Bundle bundle = new Bundle();
                bundle.putLong("custCmId", mEntity.getOrderDetails().getCUST_CM_ID());
                bundle.putString("prodSkuIds", prodSkuIds);
                bundle.putLong("customerId", mEntity.getOrderDetails().getCUSTOMER_ID());
                readyGoForResult(MembershipCardActivity.class, 0, bundle);
                break;
            case R.id.ll_order_price:
                if (!"1".equals(isFastBillingOrder)) {// if(!getIntent().getBooleanExtra("isFastCreate",false)) {
                    initPopup();
                }
            default:
                break;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        mMenu = menu;
        // Inflate the menu; this adds items to the action bar if it is present.
        if (!"1".equals(isFastBillingOrder)) {// if(getIntent().getBooleanExtra("isFastCreate",false)) {
            getMenuInflater().inflate(R.menu.order_settlement_menu, menu);
        }
        return true;
    }

    private void hiddenEditMenu() {
        if (null != mMenu) {
            for (int i = 0; i < mMenu.size(); i++) {
                mMenu.getItem(i).setVisible(false);
                mMenu.getItem(i).setEnabled(false);
            }
        }
    }

    private void showEditMenu() {
        if (null != mMenu) {
            for (int i = 0; i < mMenu.size(); i++) {
                mMenu.getItem(i).setVisible(true);
                mMenu.getItem(i).setEnabled(true);
            }
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_detail) {
            initPopup();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            memberId = data.getLongExtra("memberId", -1);
            tvDiscountName.setText(data.getStringExtra("memberName"));
            if (data.getSerializableExtra("entity") != null) {
                handleProductData((CustCardEntity.CustomerCardListEntity) data.getSerializableExtra("entity"));
            } else {
                if (data.getFloatExtra("balance", -1) >= mEntity.getOrderDetails().getORDER_TOTAL_MONEY() / 100) {
                    totalDiscountPrice = (float) mEntity.getOrderDetails().getORDER_TOTAL_MONEY() / 100;
                } else {
                    totalDiscountPrice = (float) data.getFloatExtra("balance", -1);
                }
                for (OrderDetailEntity.OrderDetailsBean.OrderItemsListBean bean : mEntity.getOrderDetails().getOrderItemsList()) {
                    bean.setHasDiscount(false);
                }
            }
            tvDiscountPrice.setText("-￥" + new DecimalFormat("0.00").format(totalDiscountPrice));
            tvDiscountPrice.setTextColor(getResources().getColor(R.color.main_red2));
            tvPayPrice.setText("￥" + new DecimalFormat("0.00").format((payPrice - totalDiscountPrice)));
        }
    }


    /**
     * 处理计算此卡价格
     *
     * @param entity
     */
    private void handleProductData(CustCardEntity.CustomerCardListEntity entity) {
        for (OrderDetailEntity.OrderDetailsBean.OrderItemsListBean bean : mEntity.getOrderDetails().getOrderItemsList()) {
            long currentSkuId = bean.getPROD_SKU_ID();
            for (CustCardEntity.CustomerCardListEntity.MemberPackageItemListEntity itemListEntity : entity.getMemberPackageItemList()) {
                if (currentSkuId == itemListEntity.getPROD_SKU_ID()) {
                    bean.setHasDiscount(true);
                    if (bean.getAMOUNT() > itemListEntity.getSURPLUS_NUMBER()) {
                        totalDiscountPrice = totalDiscountPrice + (bean.getSALE_PRICE() * itemListEntity.getSURPLUS_NUMBER()) / 100;
                    } else {
                        totalDiscountPrice = totalDiscountPrice + (bean.getSALE_PRICE() * bean.getAMOUNT()) / 100;
                    }
                    break;

                }
            }
        }
        if (totalDiscountPrice >= mEntity.getOrderDetails().getORDER_TOTAL_MONEY() / 100) {
            totalDiscountPrice = (float) mEntity.getOrderDetails().getORDER_TOTAL_MONEY() / 100;
        }

    }

}
